package com.fiberhome.opticalbox.common;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Service;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Binder;
import android.os.Environment;
import android.os.IBinder;

import com.fiberhome.opticalbox.utils.BaseUtil;
import com.fiberhome.opticalbox.utils.LogUtil;

@SuppressLint("DefaultLocale")
public class FileSearchService extends Service {

	public static final String ACTION_SEARCHED_IMAGE = "com.fh.opticalbox.filemapping.service.FileSearchService.ACTION_SEARCHED_IMAGE";
	public static final String ACTION_SEARCHED_AUDIO = "com.fh.opticalbox.filemapping.service.FileSearchService.ACTION_SEARCHED_AUDIO";
	public static final String ACTION_SEARCHED_VIDEO = "com.fh.opticalbox.filemapping.service.FileSearchService.ACTION_SEARCHED_VEDIO";

	private final IBinder mBinder = new LocalBinder();

	private FileSearchTask fileSearchTask;
	private boolean isStart = false;

	private List<File> imageList = new ArrayList<File>();
	private List<File> audioList = new ArrayList<File>();
	private List<File> vedioList = new ArrayList<File>();

	public class LocalBinder extends Binder {
		public FileSearchService getService() {
			return FileSearchService.this;
		}
	}

	@Override public IBinder onBind(Intent intent) {
		return mBinder;
	}

	public void startSearch() {
		if (BaseUtil.hasSDCard()) {
			if (fileSearchTask == null) {
				fileSearchTask = new FileSearchTask();
			}

			if (!isStart) {
				isStart = true;

				File root = Environment.getExternalStorageDirectory();
				File DCIM = new File(root.getAbsolutePath() + File.separator + "DCIM");
				File Pictures = new File(root.getAbsolutePath() + File.separator + "Pictures");
				File Download = new File(root.getAbsolutePath() + File.separator + "Download");

				List<File> rootList = new ArrayList<File>();

				if (DCIM.exists()) {
					rootList.add(DCIM);
				}
				if (Pictures.exists()) {
					rootList.add(Pictures);
				}
				if (Download.exists()) {
					rootList.add(Download);
				}

				fileSearchTask.execute(rootList);
			}
		}
	}

	public void stopSearch() {
		if (fileSearchTask != null) {
			fileSearchTask.cancel(true);
			fileSearchTask = null;
		}
		isStart = false;
	}

	private class FileSearchTask extends AsyncTask<Object, File, Boolean> {
		private final int TYPE_ERROR = -1;
		private final int TYPE_UNKOWN = 0;
		private final int TYPE_IMAGE = 1;
		private final int TYPE_AUDIO = 2;
		private final int TYPE_VIDEO = 3;
		
		/****************************************************************
		jpg/gif/png/bmp/
	    ****************************************************************/
		
		private final String[] flag_Image = {".jpg",".jpeg", ".bmp",".gif"};
		
		private final String[] flag_Audio = { ".mp3" };
		
		/****************************************************************
			微软视频 ：wmv
			Real Player ：rm、 rmvb
			MPEG视频 ：mpg、mpeg
			手机视频 ：3gp
			Apple视频 ：mov
			Sony视频 ：mp4
			其他常见视频：avi flv mkv 
		****************************************************************/
		private final String[] flag_Video = {".wmv",".rm",".rmvb",".mpg",".mpeg",".3gp",".mp4",".avi",".mov",".flv",".mkv"};

		@SuppressWarnings("unchecked") @Override protected Boolean doInBackground(Object... params) {
			if (params == null || params.length < 1) {
				// null or error root file
				return false;
			}

			try {
				File rootFile = Environment.getExternalStorageDirectory();
				File files[] = rootFile.listFiles();
				for (File f : files) {
					if (!f.isDirectory()) {
						publishProgress(f);
					}
				}
				
				List<File> rootList = (List<File>) params[0];
				for (File root : rootList) {
					searchChildFile(root);
				}
			} catch (Exception e) {
				return false;
			}

			return true;
		}

		private void searchChildFile(File root) {
			File files[] = root.listFiles();
			if (files != null) {
				for (File f : files) {
					if (".thumbnails".equals(f.getName())) {
						continue;
					}

					if (f.isDirectory()) {
						searchChildFile(f);
					} else {
						publishProgress(f);
					}
				}
			}
		}

		@Override protected void onProgressUpdate(File... values) {
			File searchedFile = values[0];
			if (searchedFile.length() == 0) {
				LogUtil.e("FileSearchService FileSearchTask onProgressUpdate() error file ! size : 0");
				return;
			}

			switch (obtainFileType(searchedFile)) {
			case TYPE_IMAGE:
				imageList.add(searchedFile);
				sendSearchingBroadcast(ACTION_SEARCHED_IMAGE);
				LogUtil.d("FileSearchService FileSearchTask onProgressUpdate() image file" + searchedFile.getAbsolutePath());
				break;
			case TYPE_AUDIO:
				audioList.add(searchedFile);
				sendSearchingBroadcast(ACTION_SEARCHED_AUDIO);
				LogUtil.d("FileSearchService FileSearchTask onProgressUpdate() audio file" + searchedFile.getAbsolutePath());
				break;
			case TYPE_VIDEO:
				vedioList.add(searchedFile);
				sendSearchingBroadcast(ACTION_SEARCHED_VIDEO);
				LogUtil.d("FileSearchService FileSearchTask onProgressUpdate() video file " + searchedFile.getAbsolutePath());
				break;
			case TYPE_ERROR:
			case TYPE_UNKOWN:
			default:
				LogUtil.d("FileSearchService FileSearchTask onProgressUpdate() untreated file !" + searchedFile.getName());
				break;
			}
		}

		private int obtainFileType(File file) {
			if (file == null) {
				return TYPE_ERROR;
			}
			String fileType = file.getName().toLowerCase();
			for (int i = 0; i < flag_Image.length; i++) {
				if (fileType.endsWith(flag_Image[i])) {
					return TYPE_IMAGE;
				}
			}

			for (int i = 0; i < flag_Audio.length; i++) {
				if (fileType.endsWith(flag_Audio[i])) {
					return TYPE_AUDIO;
				}
			}

			for (int i = 0; i < flag_Video.length; i++) {
				if (fileType.endsWith(flag_Video[i])) {
					return TYPE_VIDEO;
				}
			}

			return TYPE_UNKOWN;
		}
	}

	private void sendSearchingBroadcast(String searchedFileType) {
		Intent intent = new Intent(searchedFileType);
		sendBroadcast(intent);
	}

	@Override public void onDestroy() {
		super.onDestroy();
		stopSearch();
	}

	public FileSearchTask getFileSearchTask() {
		return fileSearchTask;
	}

	public List<File> getImageList() {
		return imageList;
	}

	public List<File> getAudioList() {
		return audioList;
	}

	public List<File> getVedioList() {
		return vedioList;
	}
}
